package com.ruoyi.source.websocket.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.source.api.domain.SrcCheckRecord;
import com.ruoyi.source.service.CheckRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
//@EnableScheduling
public class CheckWebSocket {
    @Autowired
    private CheckRecordService checkRecordService;

    @Scheduled(fixedRate = 5 * 1000)
    public String send() throws IOException {
        List<Map<String,Object>> srcCheckRecords = checkRecordService.selectCheckRecords();
        List<String> typeList = new ArrayList<>();
        List<Long> countList = new ArrayList<>();

        srcCheckRecords.stream()
                        .filter(x -> x.get("checkType") != null)
                        .forEach(x ->typeList.add(x.get("checkType").toString()));
        srcCheckRecords.stream()
                        .filter(x -> x.get("numbers") != null)
                        .forEach(x ->countList.add(Long.valueOf(x.get("numbers").toString())));
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> serverMap = new HashMap<>();
        serverMap.put("checkType",typeList);
        serverMap.put("numbers",countList);
        map.put("server",serverMap);
        map.put("pie",srcCheckRecords);
        JSONObject jsonObject = new JSONObject(map);
        WebSocketServers.sendAllMessage(jsonObject.toString());
        return jsonObject.toString();

    }
}
